const app = getApp();
const http = require("../../config/api.js");
const user = require("../../utils/login.js");
Page({
  data: {
    startX: 0, //开始坐标
    startY: 0,

    historyList: [],
    pageNum: 1,
    pageSize: 10,
    isNull: false,//是否为空数据
    getBol: true,//是否允许读取
    baseUrlImg: app.globalData.baseUrlImg
  },
  onLoad: function (options) {
    // 如果未登陆，获取本地缓存历史记录
    if (!wx.getStorageSync('openid')) {
      let historyData = wx.getStorageSync('historyData') || {};
      if (!historyData.dataList) {
        this.setData({
          isNull: true
        });
      }
      this.setData({
        historyList: historyData.dataList
      })
    } else {
      this.getHistoryList();
    }
  },
  onShow:function() {
    let time = Math.round(new Date().getTime());
    let log = {
      //日志类型：unite.通用业务；visit.访问数据；click.点击数据；order.订购数据；error.错误日志
      logType: "visit",
      msg: JSON.stringify({
        mac: app.globalData.userId,
        page: "xcxmyls",
        pageName: "梨园行历史记录",
        time: time,
        appVersionName: "小程序",
        item: 65,
        nodeCode: "001000",
        project: "lyhad",
        userId: app.globalData.memberId,
        deviceId: app.globalData.userId,
        uuid: user.getUuid(),
        pageLevel: "1"
      })
    }
    this.uniteLog(log)
  },
  //跳转到专辑详情页
  gotoAlbumDetails(e) {
    console.log(e);
    let item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: '/pages/album_details/album_details?code=' + item.code
    })
  },
  //删除事件
  del: function (e) {
    let index = e.currentTarget.dataset.idx;
    if (index === 'all') {
      wx.showModal({
        title: '提示',
        content: '是否删除全部',
        success: (res) => {
          if (res.confirm) {
            this.delHistory(index);
          }
        }
      })
    } else {
      this.delHistory(index);
    }
  },
  // 删除记录
  delHistory:function(idx){
    let index = idx;
    let list = this.data.historyList || '';
    if (!wx.getStorageSync('openid')){
      app.delRecordHistory((index=='all' ? '' :list[index].code));
      if (index !== 'all') {
        list.splice(index, 1)
        this.setData({
          historyList: list
        })
      } else {
        this.setData({
          isNull: true,
          historyList: []
        });
      }
      return false;
    }
    let userData = wx.getStorageSync('openid') || '{}';
    userData = JSON.parse(userData);
    let data = {
      userId: userData.openId || '',
      resType: 5,
      range: 0,
      project: "lyhad",
      codes: [],//资源编码（数组）；空为全部删除
    }
    // 有值为单个删除，无值为全部删除
    if (index !== 'all') {
      data.codes = [list[index].code];
    } else {
      data.codes = [];
      data.range = 1;
    }

    http.lhxRequest("api_delUserPlayHis", data).then(res => {
      if (res.code === 10000000) {
        wx.showToast({
          title: '删除成功',
          icon: 'none',
          duration: 2000
        })

        if (index !== 'all') {
          list.splice(index, 1)
          this.setData({
            historyList: list
          })
        } else {
          this.setData({
            isNull: true,
            historyList: []
          });
        }
      }
    })
  },
  
  // 观看历史
  getHistoryList: function () {
    if (!this.data.getBol) {
      return false;
    }
    this.setData({
      getBol: false
    });
    let userData = wx.getStorageSync('openid') || '{}';
    userData = JSON.parse(userData);
    let data = {
      userId: app.globalData.memberId || userData.openId,
      resType: 5,
      mediaType: 1,
      project: "lyhad",
      px: 2,
      cur: this.data.pageNum,
      pageSize: this.data.pageSize
    }
    http.lhxRequest("api_getUserPlayHisResList", data).then(res => {
      if (res.code === 10000000) {
        let list = this.data.historyList || [];
        let dataList = res.albpb && res.albpb.dataList || [];
        let pageNum = this.data.pageNum;
        let isNull = this.data.isNull;
        let getBol = this.data.getBol;
        if (dataList.length >= this.data.pageSize) {
          pageNum += 1;
          getBol = true;
        } else {
          getBol = false;
        }
        list = [...list, ...dataList];
        if (list.length == 0) {
          isNull = true;
        } else {
          isNull = false;
        }
        this.setData({
          historyList: list,
          pageNum: pageNum,
          isNull: isNull,
          getBol: getBol
        })
      }
    })
  },
  // 上拉触底加载
  onReachBottom() {
    this.getHistoryList();
  },

  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.historyList.forEach(function (v, i) {
      if (v.isTouchMove)//只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      historyList: this.data.historyList
    })
  },
  //跳转到专辑详情页
  gotoAlbumDetails(e) {
    console.log(e);
    let item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: '/pages/album_details/album_details?code=' + item.code
    })
  },
  //滑动事件处理
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index,//当前索引
      startX = that.data.startX,//开始X坐标
      startY = that.data.startY,//开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    that.data.historyList.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    that.setData({
      historyList: that.data.historyList
    })
  },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var dX = end.X - start.X,
      dY = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(dY / dX) / (2 * Math.PI);
  },
  // 日志
  uniteLog(data) {
    http.lhxRequest("api_log", data).then(res => {
      if (res.code === 10000000) {
        console.log("日志")
      }
    })
  }
})